<template>
  <div class="app-car-container">
    <CustomContent>
      <template v-slot:body>
        <!-- 添加或编辑车辆列表对话框 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-collapse accordion style="
                                                                                border: 1px solid rgb(242 242 242);
                                                                                text-align: left;
                                                                                border-radius: 4px;
                                                                                background-color: rgb(242 242 242);
                                                                              ">
            <el-row>
              <el-col :span="24">
                <div style="color: rgb(51 51 51); padding: 12px 20px">
                  <i class="el-icon-info"></i>&nbsp;车辆新增指南：
                  <span style="color: rgb(163 155 155)">
                    1.上传行驶证，系统会自动识别车牌号车架号等信息
                    &nbsp;&nbsp;&nbsp;
                    2.上传保单（可不传），系统可自动识别保险在保状态
                  </span>
                </div>
              </el-col>
            </el-row>
          </el-collapse>
          <MmvTitle title="证件信息"> </MmvTitle>
          <transition name="el-zoom-in-top">
            <el-row>
              <div style="
                                                                                    padding: 5px 15px;
                                                                                    line-height: 1.25;
                                                                                    display: flex;
                                                                                    align-items: center;
                                                                                  ">
                <div style="font-weight: 600; font-size: 20px">
                  <span style="color: #ff4949; margin-right: 4px">*</span>行驶证上传
                </div>
                <div style="margin-left: 10px; color: #aaa3a3">
                  (自动识别)
                </div>
              </div>

              <el-col :span="10">
                <el-form-item prop="drivingLicenseImgFront">
                  <el-tooltip class="item" effect="dark" content="请上传行驶证图片" placement="top-end">
                    <el-form-item label="" style="margin-top: 50px">
                      <imageUpload v-model="form.drivingLicenseImgFront" ref="imageUpload1" @success="postXsz"
                        v-bind:isShowTip="upload.isShowChildTip" v-bind:limit="upload.limit" />
                    </el-form-item>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="车牌号" prop="carNo">
                  <el-input v-model="form.carNo" maxlength="8" placeholder="请输入车牌号" class="el-input-style" />
                </el-form-item>
                <el-form-item label="车架号" prop="vinNo">
                  <el-input v-model="form.vinNo" placeholder="请输入车架号" maxlength="17" class="el-input-style" />
                </el-form-item>
                <el-form-item label="发动机号" prop="engineNo">
                  <el-input v-model="form.engineNo" placeholder="请输入发动机号" class="el-input-style" />
                </el-form-item>
                <el-form-item label="注册日期" prop="drivingLicenseValidityDate">
                  <el-date-picker clearable size="small" v-model="form.drivingLicenseValidityDate" type="date"
                    value-format="yyyy-MM-dd" placeholder="选择行驶证注册日期" class="el-input-style">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </transition>

          <MmvTitle title="车辆信息"> </MmvTitle>
          <transition name="el-zoom-in-top">
            <el-row>
              <el-col :span="24">
                <el-form-item label="品牌/车系/车型" prop="carModelId">
                  <el-select v-model="form.carBrandId" placeholder="请选择所属品牌" @change="getSeriesList" style="width: 150px"
                    class="el-input-style" filterable remote>
                    <el-option v-for="(item, i) in brandList" :key="item.brandId" :label="item.brandName"
                      :value="item.brandId"></el-option>
                  </el-select>
                  <el-select v-model="form.carSeriesId" placeholder="请选择所属车系" @change="getModelList" style="width: 150px"
                    class="el-input-style" filterable remote>
                    <el-option v-for="(item, i) in seriesList" :key="item.seriesId" :label="item.seriesName"
                      :value="item.seriesId"></el-option>
                  </el-select>
                  <el-select v-model="form.carModelId" placeholder="请选择所属车型" class="el-input-style" filterable remote
                    style="width: 300px">
                    <el-option v-for="(item, i) in modelList" :key="item.id" :label="item.modelName"
                      :value="item.id"></el-option>
                  </el-select>
                  <div style="display: inline-block; margin-left: 8px" v-hasPermi="['car:model:add']">
                    未找到车型?
                    <el-button type="text" @click="addCarModel">添加车型</el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="归属门店" prop="belongingStoreId">
                  <el-select v-model="form.belongingStoreId" placeholder="请选择归属门店" class="el-input-style" filterable disabled
                    remote>
                    <el-option v-for="(item, i) in storeList" :key="item.storeId" :label="item.storeName"
                      :value="item.storeId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="停靠门店" prop="locatedStoreId">
                  <el-select v-model="form.locatedStoreId" placeholder="请选择停靠门店" class="el-input-style" filterable remote disabled>
                    <el-option v-for="(item, i) in storeList" :key="item.storeId" :label="item.storeName"
                      :value="item.storeId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.source != 6">

                <el-form-item label="所属公司" prop="orgSupplierId">
                  <el-select v-model="form.orgSupplierId" placeholder="请选择所属公司" class="el-input-style" filterable remote
                    style="width: 200px">
                    <el-option v-for="item in orgSupplierList" :key="item.id" :label="item.name"
                      :value="parseInt(item.id)"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="当前里程/km" prop="useMileage">
                  <el-input v-model="form.useMileage" placeholder="请输入当前里程" class="el-input-style" @keyup.native="
                    form.useMileage = oninput(form.useMileage, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保养周期/km" prop="maintenanceCycle">
                  <el-input v-model="form.maintenanceCycle" placeholder="请输入保养周期" class="el-input-style" @keyup.native="
                    form.maintenanceCycle = oninput(form.maintenanceCycle, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车辆类型" prop="hpCode">
                  <el-select v-model="form.hpCode" placeholder="请选择车辆类型" class="el-input-style" filterable remote
                    style="width: 300px">
                    <el-option v-for="item in carTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </transition>

          <MmvTitle title="资产信息">
            <el-switch slot="btn" v-model="addAsset" active-text="录入资产" inactive-text="暂不录入" @change="turnOnOff()">
            </el-switch>
          </MmvTitle>
          <transition name="el-zoom-in-top">
            <el-row v-if="addAsset">
              <el-col :span="24">
                <el-form-item label="车辆来源">
                  <el-radio-group v-model="form.source" @input="changeSource">
                    <el-radio v-for="dict in dict.type.vehicle_source" :key="dict.value" :label="parseInt(dict.value)">{{
                      dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.source == 1">
                <el-form-item label="是否分期" prop="phasedOrNot">
                  <el-radio-group v-model="form.phasedOrNot">
                    <el-radio v-for="dict in dict.type.business_yes_no" :key="'__' + dict.value"
                      :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-else-if="form.source == 2">
                <el-form-item label="经租账单" prop="rentBill">
                  <el-radio-group v-model="form.rentBill">
                    <el-radio v-for="dict in dict.type.rent_bill_type" :key="dict.value" :label="parseInt(dict.value)">{{
                      dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="assetFlag == 1 || assetFlag == 2">
                <el-form-item label="供应商" prop="supplierId">
                  <el-select v-model="form.supplierId" placeholder="请选择供应商" class="el-input-style" @change="checkSupplier"
                    filterable remote style="width: 300px">
                    <el-option v-for="item in supplierList" :key="item.id" :label="item.name"
                      :value="parseInt(item.id)"></el-option>
                  </el-select>

                  <div style="display: inline-block; margin-left: 8px">
                    未找到供应商?
                    <el-button type="text" @click="openSupplier = true">点击立即添加</el-button>
                  </div>
                </el-form-item>
              </el-col>

              <!-- 托管新增 -->
              <template v-if="assetFlag == 6">
                <el-col :span="24">
                  <el-form-item label="供应商-托管车主" prop="supplierId">
                    <el-select v-model="form.supplierId" placeholder="请选择供应商-托管车主" class="el-input-style"
                      @change="depositCheckSupplier" filterable remote style="width: 300px">
                      <el-option v-for="item in depositSupplierList" :key="item.id" :label="item.name"
                        :value="parseInt(item.id)"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="托管记录">
                    <el-table :data="form.depositRecordList" border>
                      <!-- <el-table-column _min-width="200" label="托管开始时间" align="center" prop="depositStartDate">
                        <template v-slot="scope">
                          <el-date-picker clearable size="small" v-model="scope.row.depositStartDate" type="date"
                            value-format="yyyy-MM-dd" placeholder="请选择托管开始日期" @change="timeClick">
                          </el-date-picker>
                        </template>

                      </el-table-column>
                      <el-table-column _min-width="200" label="托管结束时间" align="center" prop="depositEndDate">
                        <template v-slot="scope">
                          <el-date-picker clearable size="small" v-model="scope.row.depositEndDate" type="date"
                            value-format="yyyy-MM-dd" placeholder="请选择托管结束日期" @change="timeClick">
                          </el-date-picker>
                        </template>
                      </el-table-column> -->
                      <el-table-column _min-width="200" label="托管时间" align="center" prop="depositEndDate">
                        <template v-slot="scope">
                          <el-date-picker size="small" v-model="scope.row.depositDuration" type="daterange"
                            value-format="yyyy-MM-dd" start-placeholder="托管开始日期" end-placeholder="托管结束日期"
                            @change="timeChange(scope.$index, $event)" range-separator="至">
                          </el-date-picker>
                        </template>
                      </el-table-column>
                      <el-table-column _min-width="200" label="操作" align="center">
                        <template v-slot="scope">
                          <el-button size="mini" type="danger"
                            @click="depositDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: center;align-items: center; margin-top: 20px;">
                      <!-- <el-button type="primary" size="default" @click="addCustodyRecord">添加托管记录</el-button> -->
                      <span style="color: #5473E8;" @click="addCustodyRecord">添加托管记录</span>
                    </div>
                  </el-form-item>
                </el-col>
              </template>

              <el-col :span="12" v-if="assetFlag == 1 || assetFlag == 5">
                <el-form-item label="合同开始日期" prop="startTime">
                  <el-date-picker clearable size="small" v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="选择合同开始日期" @change="timeClick">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1 || assetFlag == 5">
                <el-form-item label="合同结束日期" prop="endTime">
                  <el-date-picker clearable size="small" v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="选择合同结束日期" @change="timeClick">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1">
                <el-form-item label="首付金额/元" prop="downPayments">
                  <el-input v-model="form.downPayments" placeholder="请输入首付金额" @keyup.native="
                    form.downPayments = oninput(form.downPayments, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1">
                <el-form-item label="分期期数" prop="numberOfPeriods">
                  <el-input v-model="form.numberOfPeriods" placeholder="请输入分期期数" @blur="balancePaymentCalculate"
                    @keyup.native="
                      form.numberOfPeriods = oninput(form.numberOfPeriods, 1, 60)
                    " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1">
                <el-form-item label="每期应付/元" prop="eachIssue">
                  <el-input v-model="form.eachIssue" @blur="balancePaymentCalculate" placeholder="请输入每期应付"
                    @keyup.native="form.eachIssue = oninput(form.eachIssue, 2)" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1">
                <el-form-item label="已还期数" prop="paidBackPeriods">
                  <el-input v-model="form.paidBackPeriods" placeholder="请输入已还期数" @blur="balancePaymentCalculate"
                    @keyup.native="
                      form.paidBackPeriods = oninput(form.paidBackPeriods, 0, 60)
                    " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1 || assetFlag == 2">
                <el-form-item label="车辆购置价格/元" prop="purchasePrice">
                  <el-input v-model="form.purchasePrice" placeholder="请输入车辆购置价格" @keyup.native="
                    form.purchasePrice = oninput(form.purchasePrice, 2)
                  " />
                </el-form-item>
              </el-col>

              <el-col :span="12" v-if="assetFlag == 5">
                <el-form-item label="已付金额" prop="amountPaid">
                  <el-input v-model="form.amountPaid" placeholder="请输入已付金额" @keyup.native="
                    form.amountPaid = oninput(form.amountPaid, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 5">
                <el-form-item label="合同金额" prop="contractAmount">
                  <el-input v-model="form.contractAmount" placeholder="请输入合同金额" @keyup.native="
                    form.contractAmount = oninput(form.contractAmount, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1 || assetFlag == 5">
                <el-form-item label="应付尾款/元" prop="balancePayment">
                  <el-input v-model="form.balancePayment" placeholder="请输入应付尾款" @keyup.native="
                    form.balancePayment = oninput(form.balancePayment, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 3">
                <el-form-item label="付款比例/%" prop="paymentProportion">
                  <el-input v-model="form.paymentProportion" type="number" max="100" min="1" placeholder="输入1~100比例"
                    @keyup.native="
                      form.paymentProportion = checkProportion(
                        form.paymentProportion
                      )
                    " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 4">
                <el-form-item label="付款金额/元" prop="paymentAmount">
                  <el-input v-model="form.paymentAmount" placeholder="请输入付款金额" @keyup.native="
                    form.paymentAmount = oninput(form.paymentAmount, 2)
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 4">
                <el-form-item label="付款日期" prop="paymentTime">
                  <el-date-picker clearable size="small" v-model="form.paymentTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="选择付款日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 5">
                <el-form-item label="付款日" prop="paymentDate">
                  <el-input v-model="form.paymentDate" type="number" max="31" min="1" placeholder="输入1~31" @keyup.native="
                    form.paymentDate = checkPaymentDateProportion(
                      form.paymentDate
                    )
                  " />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="assetFlag == 1">
                <!--                <el-form-item label="下次付款日期" prop="paymentTime">
                  <el-date-picker
                    clearable
                    size="small"
                    v-model="form.paymentTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择付款日期"
                  >
                  </el-date-picker>
                </el-form-item>-->
                <el-form-item label="付款日" prop="paymentDate">
                  <el-input v-model="form.paymentDate" type="number" max="31" min="1" placeholder="输入1~31" @keyup.native="
                    form.paymentDate = checkPaymentDateProportion(
                      form.paymentDate
                    )
                  " />
                </el-form-item>
              </el-col>
            </el-row>
          </transition>
        </el-form>
      </template>
      <template v-slot:footer>
        <div class="footer">
          <el-button type="primary" @click.native="submitForm">保存</el-button>
          <el-button type="info" plain @click.native="close">取消</el-button>
        </div>
      </template>
    </CustomContent>
    <modelsave ref="modelsave" @close="getModelList"></modelsave>

    <el-dialog title="添加供应商" :visible.sync="openSupplier" width="1000px" append-to-body>
      <el-form ref="supplierForm" :model="supplierForm" :rules="supplierRules" label-width="120px">
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="供应商类型" prop="type">
              <el-select v-model="supplierForm.type" placeholder="请选择供应商类型">
                <el-option v-for="dict in dict.type.supplier_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="supplierForm.name" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商联系人" prop="contactsPeople">
              <el-input v-model="supplierForm.contactsPeople" placeholder="请输入供应商联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactsPhone">
              <el-input v-model="supplierForm.contactsPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商地址" prop="address">
              <el-input v-model="supplierForm.address" placeholder="请输入供应商地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="addLoading" @click="addSupplier">确 定</el-button>
        <el-button @click="closeSupplier">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addBasic,
  updateBasic,
  postXsz,
  getBasic,
  postBxd,
  tenancy
} from '@/api/car/car_basic'
import {
  getCarBrandList,
  getCarSeriesList,
  getCarModelList,
  getStoreList,
} from '@/api/car/model'
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import Modelsave from '@/views/car/model/modelsave'
import { getSupplierList } from '@/api/car/repairMaintain'
import CustomContent from '@/components/custom/content.vue'
import { addSupplier } from "@/api/supplier/supplier";

export default {
  name: 'basic_edit',
  dicts: [
    'manufacturer',
    'equipmentModel',
    'vehicle_source',
    'business_yes_no',
    'rent_bill_type',
    'supplier_type',
  ],
  components: {
    MmvTitle,
    Modelsave,
    CustomContent,
  },
  data() {
    return {
      openSupplier: false,
      addLoading: false,
      supplierForm: {},
      supplierRules: {
        type: [
          {
            required: true,
            message: '供应商类型不能为空',
            trigger: 'change',
          },
        ],
        name: [
          {
            required: true,
            message: '供应商名称不能为空',
            trigger: 'change',
          },
        ],
      },
      upload: {
        title: '',
        fileSize: 5,
        limit: 1,
        isShowChildTip: false,
        isShowParentTip: true,
      },
      brandList: [],
      supplierList: [],
      orgSupplierList: [],
      depositSupplierList: [],
      carTypeList: [
        { id: "01", name: "大型汽车" },
        { id: "02", name: "小型汽车" },
        { id: "51", name: "大型新能源汽车" },
        { id: "52", name: "小型新能源汽车" },
        // {id:"03",name:"使馆汽车"},
        // {id:"04",name:"领馆汽车"},
        { id: "05", name: "境外汽车" },
        { id: "06", name: "外籍汽车" },
        // {id:"07",name:"普通摩托车"},
        // {id:"08",name:"轻便摩托车"},
        // {id:"09",name:"使馆摩托车"},
        // {id:"10",name:"领馆摩托车"},
        // {id:"11",name:"境外摩托车"},
        // {id:"12",name:"外籍摩托车"},
        // {id:"13",name:"低速车"},
        // {id:"14",name:"拖拉机"},
        // {id:"15",name:"挂车"},
        // {id:"16",name:"教练汽车"},
        // {id:"17",name:"教练摩托车"},
        // {id:"18",name:"试验汽车"},
        // {id:"19",name:"试验摩托车"},
        // {id:"20",name:"临时入境汽车"},
        // {id:"21",name:"临时入境摩托车"},
        // {id:"22",name:"临时行驶车"},
        // {id:"23",name:"警用汽车"},
        // {id:"24",name:"警用摩托"},
        // {id:"25",name:"原农机号牌"},
        // {id:"26",name:"香港入出境车"},
        // {id:"27",name:"澳门入出境车"}
      ],
      seriesList: [],
      modelList: [],
      storeList: [],
      addDevice: false,
      certificatesInfo: true,
      carInfo: true,
      addBusiness: false,
      addCompulsory: false,
      addAsset: true,
      // 表单参数
      form: {
        drivingLicenseImgFront: null,
        syPolicy: null,
        jqPolicy: null,
        source: 1,
        phasedOrNot: 1,
        rentBill: 1,
      },
      // 表单校验
      rules: {
        drivingLicenseImgFront: [
          {
            // required: true,
            message: '请上传行驶证图片',
            trigger: 'change',
          },
        ],
        carNo: [
          {
            required: true,
            message: '车牌号不能为空',
            trigger: 'change',
          },
        ],
        vinNo: [
          {
            required: true,
            message: '车架号不能为空',
            trigger: 'change',
          },
        ],
        carBrandId: [
          {
            required: true,
            message: '所属品牌不能为空',
            trigger: 'change',
          },
        ],
        carSeriesId: [
          {
            required: true,
            message: '所属车系不能为空',
            trigger: 'change',
          },
        ],
        carModelId: [
          {
            required: true,
            message: '所属品牌/车系/车型不能为空',
            trigger: 'change',
          },
        ],
        belongingStoreId: [
          {
            required: true,
            message: '归属门店不能为空',
            trigger: 'change',
          },
        ],
        locatedStoreId: [
          {
            required: true,
            message: '停靠门店不能为空',
            trigger: 'change',
          },
        ],
        supplierId: [
          {
            required: true,
            message: '供应商不能为空',
            trigger: 'change',
          },
        ],
        startTime: [
          {
            required: true,
            message: '合同开始日期不能为空',
            trigger: 'change',
          },
        ],
        endTime: [
          {
            required: true,
            message: '合同开始日期不能为空',
            trigger: 'change',
          },
        ],
        downPayments: [
          {
            required: true,
            message: '首付金额不能为空',
            trigger: 'change',
          },
        ],
        numberOfPeriods: [
          {
            required: true,
            message: '分期期数不能为空',
            trigger: 'change',
          },
        ],
        eachIssue: [
          {
            required: true,
            message: '每期应付不能为空',
            trigger: 'change',
          },
        ],
        paidBackPeriods: [
          {
            required: true,
            message: '已还期数不能为空',
            trigger: 'change',
          },
        ],
        purchasePrice: [
          {
            required: true,
            message: '车辆购置价格不能为空',
            trigger: 'change',
          },
        ],
        balancePayment: [
          {
            required: true,
            message: '应付尾款不能为空',
            trigger: 'change',
          },
        ],
        paymentProportion: [
          {
            required: true,
            message: '付款比例不能为空',
            trigger: 'change',
          },
        ],
        paymentAmount: [
          {
            required: true,
            message: '付款金额不能为空',
            trigger: 'change',
          },
        ],
        paymentTime: [
          {
            required: true,
            message: '付款日期不能为空',
            trigger: 'change',
          },
        ],
        paymentDate: [
          {
            required: true,
            message: '付款日不能为空',
            trigger: 'change',
          },
        ],
        maintenanceCycle: [
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2})))$/,
            message: '保养周期输入有误',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    assetFlag() {
      if (this.form.source == 1) {
        if (this.form.phasedOrNot == 1) {
          return 1
        } else {
          return 2
        }
      }
      if (this.form.source == 6) {
        return 6
      }
      if (this.form.source == 2) {
        if (this.form.rentBill == 1) {
          return 3
        } else if (this.form.rentBill == 2) {
          return 4
        } else {
          return 5
        }
      }
      return 1
    },
  },
  created() {
    if (this.$route.query.id) {
      this.handleUpdate(this.$route.query.id)
    }
  },
  mounted() {
    getSupplierList(1).then((response) => {
      this.supplierList = response.data
    })
    getSupplierList(5).then((response) => {
      this.orgSupplierList = response.data

    })
    getSupplierList(6).then((response) => {
      this.depositSupplierList = response.data
      this.closeSupplier()
    })
  },
  methods: {
    changeSource(e) {
      if (e == 6) {//托管
        this.form.orgSupplierId = null;
      }
      this.form.supplierId = null;
      this.form.supplierName = null;
      console.log(this.form.supplierId);
    },
    // 托管时间发生改变出发
    timeChange(index, e) {
      this.form.depositRecordList[index].depositStartDate = e[0];
      this.form.depositRecordList[index].depositEndDate = e[1];
    },
    //添加托管记录
    addCustodyRecord() {
      const objRecord = {
        depositStartDate: null,
        depositEndDate: null,
        depositDuration: ['', '']
      }
      this.form.depositRecordList.push(objRecord);
    },
    //删除托管记录
    depositDelete(index, row) {
      this.form.depositRecordList.splice(index, 1)
    },

    //计算尾款自购分期
    balancePaymentCalculate() {
      if (this.form.paidBackPeriods != null && this.form.eachIssue && this.form.numberOfPeriods) {
        this.form.balancePayment = (this.form.numberOfPeriods - this.form.paidBackPeriods) * this.form.eachIssue;
      }
    },
    timeClick() {
      if (this.form.startTime && this.form.endTime && this.assetFlag == 1) {
        tenancy(this.form).then((response) => {
          this.$set(this.form, 'numberOfPeriods', response.data);
        })
      }
    },
    turnOnOff() {
      if (this.addAsset) {
        this.$set(this.form, 'source', 1);
        this.$set(this.form, 'phasedOrNot', 2);
      } else {
        this.$set(this.form, 'source', null);
        this.$set(this.form, 'phasedOrNot', null);
      }
    },
    addSupplier() {
      this.addLoading = true
      this.$refs['supplierForm'].validate((valid) => {
        if (!valid) {
          this.addLoading = false
          return false
        } else {
          addSupplier(this.supplierForm)
            .then((res) => {
              this.$modal.msgSuccess('新增成功')
              getSupplierList(1).then((response) => {
                this.supplierList = response.data
                this.closeSupplier()
              })
            })
            .finally((re) => {
              this.addLoading = false
            })
        }
      })
    },
    closeSupplier() {
      this.supplierForm = {
        id: null,
        type: null,
        name: null,
        contactsPeople: null,
        contactsPhone: null,
        address: null,
      }
      this.resetForm('supplierForm')
      this.openSupplier = false
    },
    depositCheckSupplier() {
      this.form.supplierName = this.depositSupplierList.filter((item) => {
        if (item.id == this.form.supplierId) {
          return item.name
        }
      })[0].name
    },
    checkSupplier() {
      this.form.supplierName = this.supplierList.filter((item) => {
        if (item.id == this.form.supplierId) {
          return item.name
        }
      })[0].name
    },
    addCarModel() {
      this.$refs.modelsave.handleAdd()
    },
    postXsz() {
      postXsz({ url: this.form.drivingLicenseImgFront }).then((res) => {
        this.form.carNo = res.data.carPlateNo //号牌号码
        this.form.engineNo = res.data.engineNo //发动机号码
        this.form.vinNo = res.data.vinNo //发动机号码
        this.form.drivingLicenseValidityDate = res.data.registerDate //行驶证注册日期
        // this.form.carType = res.data.carType //车辆类型
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      getCarBrandList().then((response) => {
        this.brandList = response.data
      })
      getStoreList().then((response) => {
        this.storeList = response.data
      })
      this.reset()
    },
    /** 编辑按钮操作 */
    handleUpdate(pid) {
      this.reset()
      this.addAsset = false;
      const id = pid || this.ids
      getBasic(id).then((response) => {
        this.brandList = response.data.brandList
        this.seriesList = response.data.seriesList
        this.modelList = response.data.modelList
        this.storeList = response.data.storeList
        this.form = {
          ...response.data.carBasic,
          ...response.data.assetInformation,
          id:response.data.carBasic.id

        }
        if (response.data.assetInformation) {
          this.form.source = response.data.assetInformation.source;
          this.form.supplierId = response.data.assetInformation.supplierId;
          this.form.supplierName = response.data.assetInformation.supplierName;
        }
        if (null != this.form.accessoryItems) {
          this.form.accessoryItemArray = this.form.accessoryItems.split(',')
        }
        if (null != this.form.accessoryItemsNameArray) {
          this.form.accessoryItemsNameArray =
            this.form.accessoryItemsName.split(',')
        }
        if (null == this.form.depositRecordList) {
          this.form.depositRecordList = [];
        } else {
          if (this.form.depositRecordList.length > 0) {
            this.form.depositRecordList.forEach((item) => {
              this.$set(item, 'depositDuration', [item.depositStartDate, item.depositEndDate]);
            })
          }
        }
        this.addAsset = this.form.source != null ? true : false;
      })
    },
    // 获取车系
    getSeriesList(carBrandId) {
      this.form.carSeriesId = null
      this.form.carModelId = null
      this.seriesList = []
      this.modelList = []
      getCarSeriesList(carBrandId).then((response) => {
        this.seriesList = response.data
      })
    },
    // 获取车型
    getModelList() {
      this.form.carModelId = null
      this.modelList = []
      getCarModelList(this.form.carSeriesId).then((response) => {
        this.modelList = response.data
      })
    },
    checkProportion(val) {
      val = val.replace(/[^\d.]/g, '') //保留数字
      val = val.replace(/^00/, '0.') //开头不能有两个0
      val = val.replace(/^\./g, '0.') //开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') //两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') //只保留一个小数点
        ; /^0\d+/.test(val) ? (val = val.slice(1)) : '' //两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + 0 + '}).*$'
      const reg = new RegExp(str)
      val = val.replace(reg, '$1')
      if (Number(val) < 1) {
        val = 1
      }
      if (Number(val) > 100) {
        val = 100
      }
      return val
    },
    checkPaymentDateProportion(val) {
      val = val.replace(/[^\d.]/g, '') //保留数字
      val = val.replace(/^00/, '0.') //开头不能有两个0
      val = val.replace(/^\./g, '0.') //开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') //两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') //只保留一个小数点
        ; /^0\d+/.test(val) ? (val = val.slice(1)) : '' //两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + 0 + '}).*$'
      const reg = new RegExp(str)
      val = val.replace(reg, '$1')
      if (Number(val) < 1) {
        val = 1
      }
      if (Number(val) > 31) {
        val = 31
      }
      return val
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        drivingLicenseImgFront: null,
        carNo: null,
        vinNo: null,
        engineNo: null,
        drivingLicenseValidityDate: null,

        carBrandId: null,
        carSeriesId: null,
        carModelId: null,
        locatedStoreId: null,
        belongingStoreId: null,
        currentMile: null,
        nextMile: null,

        deviceNo: null,
        simCard: null,
        manufacturer: null,
        equipmentModel: null,
        deviceKind: 1,
        belongingStoreName: null,
        locatedStoreName: null,

        syPolicy: null,
        syNo: null,
        syCompany: null,
        syStartTime: null,
        syEndTime: null,
        jqPolicy: null,
        jqNo: null,
        jqCompany: null,
        jqStartTime: null,
        jqEndTime: null,

        depositRecordList: [],
      }
      this.resetForm('form')
    },
    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //门店
          this.storeList.forEach((store, index) => {
            if (this.form.belongingStoreId == store.storeId) {
              this.form.belongingStoreName = store.storeName
            }
            if (this.form.locatedStoreId == store.storeId) {
              this.form.locatedStoreName = store.storeName
            }
          })
          if (this.form.id != null) {
            this.form.addAsset = this.addAsset
            updateBasic(this.form).then((response) => {
              this.$modal.msgSuccess('编辑成功')
              this.$emit('getList')
              this.close()
            })
          } else {
            this.form.addAsset = this.addAsset
            addBasic(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.$emit('getList')
              this.close()
            })
          }
        }
      })
    },
  },
}
</script>
<style scoped="scoped">
::v-deep .el-input__inner {
  width: 300px;
}

::v-deep .el-card__body {
  padding: 15px 20px 0px 20px;
}

::v-deep .el-row {
  margin: 0px !important;
}

::v-deep .el-card {
  margin: 12px 0 0 !important;
}

::v-deep .el-card.is-always-shadow {
  box-shadow: 0px 0 5px rgb(0 21 41 / 5%);
}
</style>
